package com.wxh.lock;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @ClassName: TestCountDownLatch
 * @Description: 倒计时锁：运动员跑步
 * @Author wxh
 * @Date: 2022/2/9 16:09
 * @Version V1.0.0
 * @Since 1.8
 */
public class TestCountDownLatch {
    private CountDownLatch countDownLatch = new CountDownLatch(5);

    /**
     * 使一个线程等待其他线程各自执行完毕后再执行
     * @param args
     */
    public static void main(String[] args) {
        TestCountDownLatch testCountDownLatch = new TestCountDownLatch();
        testCountDownLatch.begin();
    }

    /**
     * 运动员
     */
    private class Runner implements Runnable{
        private int result;
        public Runner(int result){
            this.result = result;
        }

        @Override
        public void run() {
            try {
                // 模拟跑了多少秒
                Thread.sleep(result * 1000);
                // 跑完，计数器减去1
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void begin(){
        System.out.println(" 赛跑开始 ");
        Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < 4; i++) {
            // 随机设置运动员跑多少秒
            int result = random.nextInt(3) + 1;
            new Thread(new Runner(result)).start();
        }
        System.out.println("所有人都跑完，裁判开始算成绩");
    }
}
